import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import type { RootState } from "../../app/store";
import axios from "@/util/http";

export type ResUserInfo = {
	avatar: string;
	created: string;
	has_person_info: boolean;
	phone: string;
	role: string;
	topic_role: Array<string>;
};
type Role = "student" | "admin" | "super_admin";

export type UserInfo = {
	created: Date; // 时间
	name: string; // 学生花名
	vChat: string; // 微信名字
	phone: string; // 手机
	avatar: string; // 头像
	graduation_time: Date; // 毕业时间
	money: number; // 现在薪资
	role: Role; // 角色
	_id: string;
	has_person_info: boolean; // 是否填写个人信息
	topic_role: []; // 课程权限列表
	techStack: string; // 技术栈
};

type ResMenuItem = {
	key: string;
	label: string;
	path: string;
};

const initialState = {
	userInfo: {},
	menu: [] as ResMenuItem[],
};

export const getUserInfo = createAsyncThunk<UserInfo>(
	"user/getUserInfo",
	async () => {
		const res = await axios.get("/api/user");
		return res.data.data;
	}
);

export const getMenu = createAsyncThunk("user/getMenu", async () => {
	const res = await axios.get("/api/user/menu");

	return res.data.data;
});

export const userInfoSlice = createSlice({
	name: "user",
	initialState,
	reducers: {
		setUserInfo: (state, action) => {
			state.userInfo = action.payload;
		},
	},
	extraReducers: (builder) => {
		builder.addCase(getUserInfo.fulfilled, (state, action) => {
			state.userInfo = action.payload;
		});
		builder.addCase(getMenu.fulfilled, (state, action) => {
			let arr: ResMenuItem[] = [];
			action.payload.forEach((item: ResMenuItem) => {
				arr.push({
					key: item.key,
					label: item.label,
					path: item.path,
				});
			});
			state.menu = arr;
		});
	},
});

export const { setUserInfo } = userInfoSlice.actions;
export const select_userInfo = (state: RootState): UserInfo =>
	state.userInfo.userInfo;
export const select_menu = (state: RootState) => state.userInfo.menu;

export default userInfoSlice.reducer;
